﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using FlexiCommerce.Engine;
using System.Collections;
using FlexiCommerce.Components;

namespace FlexiCommerce.Web.UI.WebControls
{
    public abstract class ItemDataSource<T> : DataSourceControl where T:PersistenceItem
    {
        public const string QueryViewName = "Query";

        private IQueryable<T> query;
        private QueryDataSourceView<T> queryView = null;

        #region Public Properties

        #region ChildrenView Specific

        /// <summary>Gets or sets whether an exception should be thrown if the given path is invalid or does not match any item.</summary>
        public bool ThrowOnInvalidPath
        {
            get { return (bool)(ViewState["ThrowOnInvalidPath"] ?? true); }
            set { ViewState["ThrowOnInvalidPath"] = value; }
        }

        public string ZoneName
        {
            get { return (string)ViewState["ZoneName"]; }
            set { ViewState["ZoneName"] = value; }
        }

        public bool PageFilter
        {
            get { return (bool)(ViewState["PageFilter"] ?? false); }
            set { ViewState["PageFilter"] = value; }
        }

        public bool NavigationFilter
        {
            get { return (bool)(ViewState["NavigationFilter"] ?? false); }
            set { ViewState["NavigationFilter"] = value; }
        }

        public string SortBy
        {
            get { return (string)ViewState["SortBy"]; }
            set { ViewState["SortBy"] = value; }
        }

        #endregion

        #region QueryView Specific

        public IQueryable<T> Query
        {
            get { return query; }
            set
            {
                query = value;
                GetQueryView().Query = value;
            }
        }

        #endregion

        #endregion

        #region Methods

        protected virtual IEngine Engine
        {
            get { return FlexiCommerce.Context.Current; }
        }

        protected virtual QueryDataSourceView<T> GetQueryView()
        {
            if (queryView == null)
            {
                queryView = new QueryDataSourceView<T>(Engine, this, QueryViewName, Query);
            }
            return queryView;
        }

        #endregion

  
     

        protected override ICollection GetViewNames()
        {
            return new string[] { QueryViewName };
        }

        protected override DataSourceView GetView(string viewName)
        {
                return GetQueryView();
        }
    }
}
